package org.gdstash.ui.font;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.Document;

public class SelectionListener implements ListSelectionListener {
    private FieldListener fieldListener;
    private JList list;
    private JTextField textField;

    public void setFieldListener(final FieldListener fieldListener) {
        this.fieldListener = fieldListener;
    }

    public void setList(final JList list) {
        this.list = list;
    }

    public void setTextField(final JTextField textField) {
        this.textField = textField;
    }

    @Override
    public void valueChanged(final ListSelectionEvent event) {
        this.setFieldValue();
    }

    private void setFieldValue() {
        final Document document = this.textField.getDocument();
        document.removeDocumentListener(this.fieldListener);
        final Object object = this.list.getSelectedValue();
        if (object != null) {
            this.textField.setText(object.toString());
        }
        document.addDocumentListener(this.fieldListener);
    }
}
